package com.newear.marathon.service.impl;

import com.newear.marathon.entity.admin.AdminResource;
import com.newear.marathon.entity.admin.AdminUser;
import com.newear.marathon.service.IAdminResourceService;
import com.newear.marathon.service.IAdminRoleService;
import com.newear.marathon.service.IAdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author MicroBin
 * @description：TODO
 * @date 2021/4/21 8:40 下午
 */
@Component("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService
{

    @Autowired
    private IAdminUserService adminUserService;
    @Autowired
    private IAdminRoleService adminRoleService;
    @Autowired
    private IAdminResourceService adminResourceService;

    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException
    {
        //根据登录名查询用户信息
        AdminUser adminUser = adminUserService.findByUsername(username);
        if (adminUser == null)
        {
            throw new UsernameNotFoundException("未查询到有效用户信息");
        }
        List<GrantedAuthority> authorityList = new ArrayList<>();
        /*List<AdminRole> roleList = adminRoleService.findByUserId(adminUser.getId());
        for (AdminRole role : roleList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role.getId());
            authorityList.add(authority);
        }*/
        List<AdminResource> resourceList = adminResourceService.findByUserId(adminUser.getId());
        for (AdminResource resource : resourceList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(resource.getPermission());
            authorityList.add(authority);
        }
        User user = new User(adminUser.getUsername(), adminUser.getPassword(), true, true, true, true, authorityList);
        return user;
    }
}
